﻿YFNBA = function(){

	var _ajaxGetHtml = null;

	var TEAM_INFO = function() {
		// private
		var _leagueInfo = [];
		var _leagueId = 0;
		var _ti = [];

		// public methods
		return {
			// 取得league資訊
			init: function(leagueInfo, url, callback) {	// http://basketball.fantasysports.yahoo.com/nba/11950/9
				_leagueInfo = leagueInfo? leagueInfo: [];
				var i = url.indexOf('/nba/') + 5;
				var j = url.indexOf('/', i);
				if(j>0){
					url = url.substring(0, j);
				}
				url += '?lhst=stand#lhststand';
				_leagueId = parseInt(url.substring(i, url.length), 10);
				// get league page
				$.get(url,	function(html){
					TEAM_INFO.ajaxOnProcessLeagueInfo(gm.Html.getHtmlBody(html));
					callback();
				});
			},

			//
			parseUrlInfo: function(){
				gm.log('parseUrlInfo');
				//gm.url_params
				// http://basketball.fantasysports.yahoo.com/nba/11950/9
				gm.url_params.league_id = _leagueId;

				var s = gm.url;
				var i = s.indexOf('/nba/')+5;
				s = s.substring(i, s.length);
				i = s.indexOf('/');
				if(i<0){ // team_id
					gm.url_params.team_id = TEAM_INFO.getTeamIdByLid(_leagueId);
					gm.url_params.team_name = TEAM_INFO.getTeamNameByLid(_leagueId);
				}else{
					s = s.substring(i+1, s.length);
					i = s.indexOf('/');
					if(i>0){
						s = s.substring(0, i);
					}
					gm.url_params.team_id = isNaN(parseInt(s, 10))? TEAM_INFO.getTeamIdByLid(_leagueId) : parseInt(s, 10);
					gm.url_params.team_name = TEAM_INFO.getTeamNameByTid(gm.url_params.team_id);
				}
			},

			ajaxOnProcessLeagueInfo: function(html){
				gm.log('ajaxOnProcessLeagueInfo');
				var div = gm.Dom.insertHddenHtml(html);
				try{
					var as = gm.Dom._x('//div[@id="'+div.id+'"]//td[@class="team"]/a');
					$.each(as, function(i, a){
						var url = a.href;
						var j = url.lastIndexOf('/');
						var team_id = parseInt(url.substring(j+1, url.length), 10);
						var team_name = a.innerHTML;
						gm.log('[{0}: {1}]', team_id, team_name);
						_ti[team_id] = team_name;
					});
				}finally{
					div.innerHTML = '';
					TEAM_INFO.parseUrlInfo();
				}
			},

			getTeamId: function(team_name) {
				for(var i=1; i<_ti.length; i++){
					if(_ti[i] == team_name) {return i;}
				}
				return 0;	// not found
			},

			getTeamNameByTid: function(team_id) {
				gm.log('getTeamNameByTid');
				return _ti[team_id];
			},

			getTeamNameByLid: function(lid) {
				gm.log('getTeamNameByLid');
				for(var i=0; i<_leagueInfo.length; i++){
					if(_leagueInfo[i].lid == lid){	return _leagueInfo[i].tname; }
				}
				return '';	// not found
			},

			getTeamIdByLid: function(lid) {
				for(var i=0; i<_leagueInfo.length; i++){
					if(_leagueInfo[i].lid == lid){	return _leagueInfo[i].tid; }
				}
				return 0;	// not found
			}

		};
	}();

	var YSPTEAM = function() {
		// private
		var _refreshTimer = null;
		var _refreshInterval = 180;	// seconds
		var _gamesInfo = function() {
			// private
			var _games = [];	// [{gameId, status, players[]}, {}, ...], status: 0-over, 1-playing
			var _isReady = false;
			var _playerStats = {};	// [playerId]: stat
			var _statsInfo = function() {
				// private
				// 使用 yahoo 的資料
				var _stats = ['MIN', 'FG', '3PT', 'FT', 'OFF', 'REB', 'AST', 'TO', 'STL', 'BLK', 'PF', 'PTS'];
				var _statSum = {
					MIN: 0,
					FG: {M:0, A:0},
					PT3: {M:0, A:0},
					FT: {M:0, A:0},
					OFF: 0,
					REB: 0,
					AST: 0,
					TO: 0,
					STL: 0,
					BLK: 0,
					PF: 0,
					PTS: 0
				};

				// public methods
				return {
					getStats: function(){
						return _stats;
					},

					// 淸為0
					resetSum: function(){
						_statSum.MIN =
						_statSum.FG.M =
						_statSum.FG.A =
						_statSum.PT3.M =
						_statSum.PT3.A =
						_statSum.FT.M =
						_statSum.FT.A =
						_statSum.OFF =
						_statSum.REB =
						_statSum.AST =
						_statSum.TO =
						_statSum.STL =
						_statSum.BLK =
						_statSum.PF =
						_statSum.PTS = 0;
					},

					// 累加至總和
					addToSum: function(stat) {
						var i=0;
						_statSum.MIN += parseInt(stat[i++], 10);
						var s = stat[i++].split('-');
						_statSum.FG.M += parseInt(s[0],10);
						_statSum.FG.A += parseInt(s[1],10);
						s = stat[i++].split('-');
						_statSum.PT3.M += parseInt(s[0],10);
						_statSum.PT3.A += parseInt(s[1],10);
						s = stat[i++].split('-');
						_statSum.FT.M += parseInt(s[0],10);
						_statSum.FT.A += parseInt(s[1],10);
						_statSum.OFF += parseInt(stat[i++],10);
						_statSum.REB += parseInt(stat[i++],10);
						_statSum.AST += parseInt(stat[i++],10);
						_statSum.TO += parseInt(stat[i++],10);
						_statSum.STL += parseInt(stat[i++],10);
						_statSum.BLK += parseInt(stat[i++],10);
						_statSum.PF += parseInt(stat[i++],10);
						_statSum.PTS += parseInt(stat[i++],10);
					},

					// 將總和填入表格
					fillSum: function(){
						var ul = $('div.sum ul').get(0);
						$(ul).html('<li>'+_statSum.MIN+'</li>'+
							'<li>'+_statSum.FG.M+'-'+_statSum.FG.A+'</li>'+
							'<li>'+_statSum.PT3.M+'-'+_statSum.PT3.A+'</li>'+
							'<li>'+_statSum.FT.M+'-'+_statSum.FT.A+'</li>'+
							'<li>'+_statSum.OFF+'</li>'+
							'<li>'+_statSum.REB+'</li>'+
							'<li>'+_statSum.AST+'</li>'+
							'<li>'+_statSum.TO+'</li>'+
							'<li>'+_statSum.STL+'</li>'+
							'<li>'+_statSum.BLK+'</li>'+
							'<li>'+_statSum.PF+'</li>'+
							'<li>'+_statSum.PTS+'</li>');
					},

					// 加入統計欄位
					formatStatTable: function() {
						// header
						var header_tr = $('#statTable0 tr.headerRow1').get(0);
						var td_string = '';
						$.each(_stats, function(i, s){
							$(header_tr).append('<th class="stat">'+s+'</th>');
							td_string += '<td class="stat mystat">-</td>';
						});

						// body
						var trs = $('#statTable0 tbody tr');
						$.each(trs, function(i, tr){
							$(tr).append(td_string);
							var a = $('a.name', tr).get(0);	// find player link, get player id
							if(a){
								var p_id = a.href.match(/\d+/)[0];
								tr.id = 'tr_'+p_id;
							}
						});
					}

				};
			}();

			function _refreshGameStatus(){
				$.each(_games, function(i, g){
					var a = $('a[href*="gid='+g.gameId+'"]').get(0);
					// check a's innerHTML
					var s = a.innerHTML.substring(0,1);
					if(s=='W' || s=='L'){
						if(_games[i].status==1){	// playing
							_games[i].status = 2;	// going over
						}else{
							_games[i].status = 0;	// game over
						}
					}
				});
			}

			function _hilitPlayers(players) {
				$.each(players, function(i, p){
					$('tr#tr_'+p).toggleClass('update');
				});
			}

			function _fillPlayerStat(p_id, stat) {
				var tds = $('tr#tr_'+p_id+' td.mystat');
				$.each(tds, function(i, td){
					td.innerHTML = stat[i];
				});
			}

			// public methods
			return{
				init: function() {
					_statsInfo.formatStatTable();

					var as = $('td.gametime a');
					$.each(as, function(i, a){
						var g_id = a.href.match(/\d+/)[0];
						var p_id = a.parentNode.parentNode.id.split('_')[1];
						gm.log('game:{0}, player:{1}', g_id, p_id);
						for(var j=0; j<_games.length; j++){
							if(_games[j].gameId==g_id){	// found
								_games[j].players.push(p_id);
								return;
							}
						}//for
						// not found, add (gameId, player)
						_games.push({gameId: g_id, status: 1, players: [p_id]});
					});
					gm.log(_games);
					_isReady = true;
				},

				refreshScorebox: function() {
					if(!_isReady) { _gamesInfo.init(); }

					// 總和清為0
					_statsInfo.resetSum();

					// 更新比賽比數
					_ajaxGetHtml(document.location.href, _gamesInfo.ajaxOnProcessGames);

					// get score box
					$.each(_games, function(i, g){
						if(g.status >0){	// 比賽仍進行中
							//var sUrl = 'http://scores.espn.go.com/nba/boxscore?gameId='+g.gameId;		// ESPN
							var sUrl = 'http://sports.yahoo.com/nba/boxscore?gid='+g.gameId;
							gm.log(sUrl);
							_hilitPlayers(g.players);
							_ajaxGetHtml(sUrl, _gamesInfo.ajaxOnProcessScorebox, g.players);
						}else{	// 直接用 _playerStats 資料回填
							$.each(g.players, function(j, p){
								var stat = _playerStats[p];
								_fillPlayerStat(p, stat);
								_statsInfo.addToSum(stat);
								_statsInfo.fillSum();
							});
						}
					});

					// 更新比賽狀態
					_refreshGameStatus();
				},

				ajaxOnProcessGames: function(html) {
					var div = gm.Dom.insertHddenHtml(html);
					try{
						var as = $('td.gametime a');
						var asNew = $('div#'+div.id+' td.gametime a');
						if(as.length != asNew.length*2){
							gm.log('Error: as.length={0}; asNew.length={1}', as.length, asNew.length);
							return;
						}
						var len = asNew.length;
						gm.log('asNew.length={0}', len);
						for(var i=0; i<asNew.length; i++){
							$(as[i].parentNode).replaceWith(asNew[i].parentNode);
						}
					}finally{
						div.innerHTML = '';
					}
					
					// replace boxscore link to no refresh
					$.each($('td.gametime a'), function(i, a){
						a.href += '&refresh=0';
					});
				},

				ajaxOnProcessScorebox: function(html, players){
					//gm.log('ajaxOnProcessScorebox');
					//gm.log(players);
					var div = gm.Dom.insertHddenHtml(html);
					try{
						$.each(players, function(i, p){
							gm.log('p={0}', p);
							//var a = gm.Dom._x0('//div[@id="'+div.id+'"]//tr[contains(@class,"ysprow")]//a[contains(@href,"/nba/players/'+p+'")]');
							var a = $('tr[class^="ysprow"] a[href*="/nba/players/'+p+'"]', div).get(0);
							gm.log(a);
							if(a){
								//var tr = a.parentNode.parentNode;
								var tr = a.parentNode;
								while(true){
									if(tr.tagName=='TR'){ break; }
									tr = tr.parentNode;
								}
								var tds = $('td', tr);
								var stat = [];
								$.each(tds, function(i,td){
									if(i<=1 || i==6 || i==13){ return; } // 跳過前二個<td>
									stat.push($.trim(td.innerHTML).replace('&nbsp;', ''));
								});
								gm.log(stat);

								if(stat.length==_statsInfo.getStats().length){
									// log player's stat
									_playerStats[p.toString()] = stat;
									_fillPlayerStat(p, stat);
									if($('tr#tr_'+p).get(0).className.search('bench')<0){
										_statsInfo.addToSum(stat);
										_statsInfo.fillSum();
									}
								}
							}
						});

						_hilitPlayers(players);

						gm.log(_playerStats);

					}finally{
						div.innerHTML = '';
					}
				}

			};
		}();

		// public
		return {
			setRefreshInterval: function(refreshInterval){
				if(typeof refreshInterval != 'undefined'){
					ri = parseInt(refreshInterval,10);
					if(!isNaN(ri) && ri>=30){
						_refreshInterval = ri;
					}
				}
			},

			main: function(){
				// mark bench players
				$.each($('td.pos'), function(i, td){
					if(td.textContent=='BN'){
						$(td.parentNode).addClass('bench');
					}
				});

				// team menu
				var sel = $('#otherteamnavselect').get(0);
				var sel2 = $(sel).clone(true);
				$(sel).replaceWith(sel2);
				$('#otherteamnavselect').change(function(){
					gm.log('select: {0}', this.value);
					var url = 'http://basketball.fantasysports.yahoo.com/nba/' +
						gm.url_params.league_id +
						'/players?status='+this.value+'&pos=P&cut_type=33&stat1=S_AS_2009&sort=AR';
					window.open(url);
				});
				$('#otherteamnavselect').after('<input id="viewteam" type="button" class="button" value="->">');
				$('#viewteam').click(function(){
					var url = 'http://basketball.fantasysports.yahoo.com/nba/' +
						gm.url_params.league_id +
						'/players?status='+$('#otherteamnavselect').val()+'&pos=P&cut_type=33&stat1=S_AS_2009&sort=AR';
					window.open(url);
				});

				// 若有 stattracker 廣告, remove it
				if($('div#statspromo').get(0)){
					$('div#statspromo').remove();	// remove ad
					$('.statspromo').remove();		// remove ad
				}

				// 加入Sitchu link
				// http://www.sitchu.com/livestatspage.aspx?playerList=47,48,49,186&benchList=47,49
				var urlSitchu = 'http://www.sitchu.com/api/stats-service/v1/players/getIDsFromNames.aspx?output=json&names=';
				$.each($('.player a.name'), function(i, a){
					urlSitchu += a.innerHTML + ',';
				});
				urlSitchu = urlSitchu.substring(0, urlSitchu.length-1);	// 去掉結尾逗號
				gm.log('urlSitchu={0}', urlSitchu);
				_ajaxGetHtml(urlSitchu, function(json){
					var playerIDs;
					eval('playerIDs=' + json);
					var url = 'http://www.sitchu.com/livestatspage.aspx?playerList=';
					$.each(playerIDs, function(i,pid){
						var benches = $('tr.bench[id^="tr_"]').length;
						if(i==playerIDs.length-benches){
							// 去掉結尾逗號
							url = url.substring(0, url.length-1) + '&benchList=';
						}
						url += pid + ',';
					});
					gm.log(url);
					var ul = $('div#datenav ul').get(0);
					$(ul).after('<input id="openSitchu" type="button" class="button" value="Sitchu">');
					$('input#openSitchu').click(function(){
						window.open(url, '_blank');
					});
				});


				// 是否加入更新功能
				//if(!$('#statTable0 th.stat').get(0)){
				var lis = $('div.sum li');
				var isUpdate=true;
				for(var i=0; i<lis.length; i++){
					if(lis[i].textContent!='-')	{
						isUpdate=false;
						break;
					}
				}
				if(lis.length>0 && isUpdate){
					// 若有stat, 移除
					$('#statTable0 th.stat').remove();
					$('#statTable0 td.stat').remove();
					// 更新
					_gamesInfo.refreshScorebox();

					// 加入更新 button
					var ul = $('div#datenav ul').get(0);
					$(ul).after('<input id="scorebox" type="button" class="button" value="Refresh"><input id="autoupdate" type="button" class="button" value="AutoRefresh">');
					$('input#scorebox').click(YSPTEAM.refreshScorebox);
					$('input#autoupdate').click(function(){
						//gm.log(this.value);
						//gm.log(_refreshTimer);
						if(_refreshTimer){
							window.clearInterval(_refreshTimer);
							_refreshTimer = null;
							this.value = 'AutoRefresh';
						}else{
							_refreshTimer = window.setInterval(function(){YSPTEAM.onRefresh();}, 1000);
							this.value = _refreshInterval + '(s)';
						}
					});
				}

				// 標註球員是否有比賽
				function _setPlayerGaming(){
					$.each( $('td.opp'), function(i, td){
						//$(td.parentNode).addClass(td.textContent.trim()==''? 'nogame': 'playgame');
						if(td.textContent.trim()===''){
							$(td.parentNode).toggleClass('nogame');
						}
					});
				}
				_setPlayerGaming();
				// 顯示所有球員
				ul = $('div#datenav ul').get(0);
				$(ul).after('<input id="showplayer" type="button" class="button" value="Player">');
				$('input#showplayer').click(_setPlayerGaming);
			},

			onRefresh: function() {
				var button = $('input#autoupdate').get(0);
				button.value = (parseInt(button.value,10)-1) + '(s)';
				if(button.value=='-1(s)'){
					button.value = _refreshInterval + '(s)';
					YSPTEAM.refreshScorebox();
				}
			},

			refreshScorebox: function() {
				_gamesInfo.refreshScorebox();
			}

		};	// return
	}();

	function _init() {
		function init_changePlayerLinks() {
			$.each( $('a.name'), function(i, a){
				a.target = a.href.match(/\d+$/)[0];
				a.href += '/gamelog';
			});
		}

		function init_changeLinks() {
			try{
				// Players => players?status=A&pos=P&cut_type=33&stat1=S_AS_2009&sort=AR
				$('div#yspnav a[href*="/players"]').get(0).href +=
					'?status=A&pos=P&cut_type=33&stat1=S_AS_2009&sort=AR';
			}catch(e){}

			try{
				// Watch List => playerswatch?stat1=AS&stat2=AS_2009&sort=AR
				$('div#yspsubnav a[href*="/playerswatch"]').get(0).href +=
					'?stat1=AS&stat2=AS_2009&sort=AR';
			}catch(e2){}
		}

		function init_addMenuItem() {
			var lis = $('#yspsubnav ul li');
			var li = lis.get(lis.length-2);
			var newli = $(li).clone();
			newli.html('<a href="http://basketball.fantasysports.yahoo.com/nba/'+gm.url_params.league_id+'/standings">Standing</a>');
			$(li).after(newli);
		}

		// ---------------------------------------------------------

		// 改變標題
		document.title = gm.url_params.team_name + '-' +
			$('body').get(0).id.replace('ysp', '');

		// 加入選單
		init_addMenuItem();

		// 於新視窗開啟連結
		$.each($('#yspnav a, #yspsubnav a'), function(i, a){
			a.target = gm.url_params.league_id + a.textContent; //'_blank';
		});

		// 改變連結
		init_changeLinks();
		init_changePlayerLinks();

		//由 body id 決定執行那支程式
		switch( $('body').get(0).id ){
			case 'yspteam':
				YSPTEAM.main();
				break;
				
			case 'xxxxxxx':
				break;
				
			default:
				break;
		}
	}

	function _lhome(){
		// 加上排行連結
		var team_as = $('a.team');
		$.each( $('div.league a'), function(i, a){		
			$(a).after('<br>'+
				'(<a href="'+a.href+'/players?status='+team_as.get(i).href.match(/\d+$/g)[0]+'&pos=P&cut_type=33&stat1=S_AS_2009&sort=AR'+'">Me</a>'+
				' | <a href="'+a.href+'/standings'+'">S</a>'+
				' | <a href="'+a.href+'/players?status=A&pos=P&cut_type=33&stat1=S_AL7&sort=AR'+'">P</a>'+
				' | <a href="'+a.href+'/players?status=W&pos=P&cut_type=33&stat1=S_AL7&sort=AR'+'">W</a>'+
				(a.href.indexOf('273791')>0? 
					' | <a href="'+team_as.get(i).href+'/playerswatch?stat1=AS&stat2=AL7&sort=PTS'+'">Watch</a>':
					' | <a href="'+team_as.get(i).href+'/playerswatch?stat1=AS&stat2=AL7&sort=AR'+'">Watch</a>'
				)+
				')');
		});
		
		
		// 改變連結
		$.each(team_as, function(i, a){
			a.href += '/team?&stat1=AS&stat2=AL7';
		});

		// 開啟新視窗
		$.each( $('div.content a'), function(i, a){
			a.target = a.href;
		});
	}

	return{
		version: '2009.10.30',
		// ---------------------------------------------------------------------------
		// 由此啟動
		// ---------------------------------------------------------------------------
		main: function(f, options){	// 注意: 不可直接傳入 GM_xmlhttpRequest, 會導致 permittion error
			gm.log('YFNBA v{0}', this.version);
			if(!options.leagueInfo){
				alert('Please set *myOptions* in "yfnba.user.js"!');
				return;
			}

			_ajaxGetHtml = f;
			if(options.refreshInterval){
				YSPTEAM.setRefreshInterval(options.refreshInterval);
			}

			// 如果是league home, 則做完直接跳出
			if(/\/nba$/g.test(document.location)){
				_lhome();
				return;
			}
			
			// 將計分板網址取代為不更新
			$.each($('td.gametime a'), function(i, a){
				a.href += '&refresh=0';
			});

			//由 body id 決定執行那支程式 => 需立即做者
			switch( $('body').get(0).id ){
				case 'yspplayerswatch':
					if(/playerswatch$/gi.test(document.location)){
						window.location = document.location + '?stat1=AS&stat2=AS_2009&sort=AR';
						return;
					}
					break;
				
				case 'xxxxx':
					break;
				default: 
					break;
			}

			TEAM_INFO.init(options.leagueInfo, gm.url, _init);
		}

	};
}();